package com.fleapx.netty_learn.heart_beat;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * @version:: netty_heart
 * @description:
 * @create: 2021/12/5 2:37.
 */
public class HeartBeatHandler extends SimpleChannelInboundHandler <String>{
    int readIdleTimes = 0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String o) throws Exception {
        System.out.println("========>【server】 message received :" +o);
        if("I am alive".equals(o)){
            ctx.channel().writeAndFlush("copy that");
        }else {
            System.out.println("other message  client is sleep");
        }
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        ctx.fireUserEventTriggered(evt);
        IdleStateEvent evt1 = (IdleStateEvent) evt;
        String eventType = null;
        switch (evt1.state()){
            case READER_IDLE:
                readIdleTimes ++;
                eventType = "读空闲";
                break;
            case ALL_IDLE:
                eventType = "读写空闲";
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                break;
        }
        System.out.println(ctx.channel().remoteAddress()+"超时事件："+eventType);
        if(readIdleTimes>3){
            System.out.println("!!!!!!!!!!!!!!>【server】 读空闲超过3次，关闭连接 ");
            ctx.channel().writeAndFlush("you are out");
            ctx.channel().close();
        }
    }
}
